//
//  AppFlutterBridget.swift
//  Runner
//
//  Created by mini2021 on 2025/6/11.
//

import UIKit
import BTHelp
import Bugly

class AppFlutterBridge: NSObject {

    static let shared = AppFlutterBridge()
    private var channel: FlutterMethodChannel?
    
    override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector:#selector(appDidEnterForeground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector:#selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector:#selector(dataChangedFromLastPause), name: Notification.Name(KBTDateChangedFromLastPauseNotify), object: nil)
        
        
    }
    
    @objc func dataChangedFromLastPause(){
        callFlutterFunc(funcName: "dataChangedFromLastPause", data: nil)
    }
    
    @objc func appDidBecomeActive(){
        callFlutterFunc(funcName: "appDidBecomeActive", data: nil)
    }
    
    @objc func appDidEnterForeground(){
        callFlutterFunc(funcName: "appDidEnterForeground", data: nil)
    }
    
    func callFlutterFunc(funcName : String, data : Any?){
        channel?.invokeMethod(funcName, arguments: data) { result in
            
        }
    }
    
    func setBridge(controller : FlutterViewController){
        channel = FlutterMethodChannel.init(name: "bt.flutter/channel", binaryMessenger: controller.binaryMessenger)
        channel?.setMethodCallHandler { call, result in
            if(call.method == "encrypt"){
                result(self.encrypt(obj: call.arguments))
            }else if(call.method == "decrypt"){
                result(self.decrypt(obj: call.arguments))
            }else if(call.method == "getDeviceId"){
                result(self.deviceId())
            }else if(call.method == "applePay"){
                self.applePay(obj: call.arguments, callback: result)
            }else if(call.method == "deleteAppleReceipt"){
                self.deleteAppleReceipt(obj: call.arguments, callback: result)
            }else if(call.method == "restoreApplePay"){
                self.restoreApplePay(callback: result)
            }else if(call.method == "userDidLogin"){
                self.didLogin(obj: call.arguments, callback: result)
            }else if(call.method == "userDidLogout"){
                self.didLogout()
            }else if(call.method == "reportError"){
                self.reportError(obj: call.arguments)
            }else if(call.method == "checkReceipt"){
                self.checkReceipt(obj: call.arguments,callback: result)
            }else if(call.method == "getEnvConfig"){
                self.getEnvConfig(callback: result)
            }
        }
    }
    
    func getEnvConfig(callback: @escaping FlutterResult){
        if(BTEnvDefine.isRelease()){
            BTLogMananger.save("正式环境")
            callback("1")
        }else{
            callback("0")
            BTLogMananger.save("测试环境")
        }
    }
    
    func checkReceipt(obj : Any?,callback: @escaping FlutterResult){
        if let strArray = obj as? [String] {
            if (strArray.count != 1){
                return
            }
            
            let model = BTApplePay.share().checkLostReceiptModel(withUid: strArray.first!)
            var resultStr = ""
            if(model != nil){
                resultStr = model!.autoDataToJsonStr()
            }
            callback(resultStr);
        }
    }
    
    func reportError(obj : Any?){
        if let strArray = obj as? [String] {
            if (strArray.count != 1){
                return
            }
            let error = BTUtils.createError(withStr: strArray.first)
            Bugly.reportError(error)
        }
    }
    
    func didLogin(obj : Any?, callback: @escaping FlutterResult){
        if let strArray = obj as? [String] {
            if (strArray.count != 1){
                return
            }
            let dictDool = BTDictTool.create(withDict: strArray.first as NSObject?)
            
        }
    }
    
    func didLogout(){
        
    }
    
    func restoreApplePay(callback: @escaping FlutterResult){
        ApplePayTool.share().restore(callback);
    }
    
    
    func deleteAppleReceipt(obj : Any?, callback: @escaping FlutterResult){
        if let strArray = obj as? [String] {
            if (strArray.count != 1){
                return
            }
            BTApplePay.share().removeReceiptModel(strArray.first!)
        }
    }
    
    func applePay(obj: Any?, callback: @escaping FlutterResult) {
        if let strArray = obj as? [String], let dataStr = strArray.first {
            ApplePayTool.share().startPay(withDataStr: dataStr) { resultStr in
                callback(resultStr)
            }
        } else {
            callback("")
        }
    }
    
    
    func encrypt(obj : Any?) -> String{
        
        
        
        return ""
    }
    
    func decrypt(obj : Any?) -> String{
        
        return ""
    }
    
    func deviceId() ->String{
        return BTDeviceTool.identifyOri()
    }
    
}
